<?php
/**
 * Created by YUNYI.
 * User: james.xiao
 * Date: 2021-03-10
 * Time: 8:09
 */

namespace yy\helper;
use think\facade\Db;
use yy\exception\Error;


/**
 * 数据库操作类
 * Class DbUnit
 * @package app\units
 */
class DbManager
{

    /**
     * 批量插入 通过sql
     * @param string $table 表
     * @param array $data 数据 关联数组
     * @param bool $autoField 自动填充创建时间 create_time 创建人 create_id
     * @throws Error
     */
    public static function insertAllByTable(string $table ,array $data , bool $autoField = false)
    {
        if (empty($data) || empty($table)) throw new Error(400);
        if ($autoField){
            array_walk($data , function (&$v){
                $v['create_time'] = time();
                $v['create_id'] = Login::loginState('id') ?: 0;
            });
        }
        $fields = $data[0];
        $fields = "`" . join("`,`" , array_keys($fields)) . "`";
        $insertSqls = array_map(function ($v){
            return "('" . join("','" , $v) . "')";
        } , $data);
        $insertSql = "INSERT INTO {$table} ({$fields}) VALUES " . join("," , $insertSqls);
        halt($insertSql);
        Db::query($insertSql);

    }

    /**
     * 批量插入 通过sql
     * @param string $table 表
     * @param array $fields 字段
     * @param array $data 数组
     * @param bool $replace 是否用replace
     * @throws Error
     */
    public static function insertAllByTableFields(string $table ,array $fields ,array $data , $replace = false)
    {
        if (empty($data) || empty($table) || empty($fields)) throw new Error(400);
        $fields = "`" . join("`,`" , $fields) . "`";
        $insertSqls = array_map(function ($v){
            return "('" . join("','" , $v) . "')";
        } , $data);
        $insertSql = '';
        if ($replace){
            $insertSql .= "REPLACE INTO ";
        } else {
            $insertSql .= "INSERT INTO ";
        }
        $insertSql .= " {$table} ({$fields}) VALUES " . join("," , $insertSqls);

        Db::query($insertSql);

    }

    public static function getValue($sql)
    {
        $result = Db::query($sql);
        return array_pop($result[0]);
    }
}